package indi.zhifa.core.multidatasource.core.factorbean;

import com.atomikos.spring.AtomikosDataSourceBean;
import com.mysql.cj.jdbc.MysqlXADataSource;
import indi.zhifa.core.multidatasource.entity.SysDbEntity;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.boot.jdbc.DataSourceBuilder;

import javax.sql.DataSource;
import java.util.Optional;

public class SingleDataSourceFactorBean implements FactoryBean<DataSource> {

    private final SysDbEntity mSysDbEntity;

    public SingleDataSourceFactorBean(SysDbEntity pSysDbEntity) {
        mSysDbEntity = pSysDbEntity;
    }

    @Override
    public DataSource getObject() throws Exception {
        MysqlXADataSource dataSource = DataSourceBuilder.create().type(MysqlXADataSource.class)
                .url(mSysDbEntity.getDbUrl())
                .username(mSysDbEntity.getDbUser())
                .password(mSysDbEntity.getDbPasswd())
                .build();
        AtomikosDataSourceBean atomikosDataSourceBean = new AtomikosDataSourceBean();
        atomikosDataSourceBean.setUniqueResourceName(mSysDbEntity.getDbKey());
        atomikosDataSourceBean.setXaDataSourceClassName("com.mysql.cj.jdbc.XADataSource");
        atomikosDataSourceBean.setXaDataSource(dataSource);
        Optional.ofNullable(mSysDbEntity.getMinIdle()).ifPresent(atomikosDataSourceBean::setMinPoolSize);
        Optional.ofNullable(mSysDbEntity.getMaxPoolSize()).ifPresent(atomikosDataSourceBean::setMaxPoolSize);
        return atomikosDataSourceBean;
    }

    @Override
    public Class<?> getObjectType() {
        return DataSource.class;
    }
}
